import { Apimessagelist } from "../../api/index"
import { formatDate, debounce } from "../../../utils/index"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    parmas: {
      page: 1,
      size: 20,
    },
    loading: false,
    finish: false,
    list: []
  },

  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.init()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    app.ws.onList(true,this.refreshList.bind(this))
  },

  refreshList: debounce(function(data) {
    const parmas = {...this.data.parmas}
    this.data.parmas = {page: 1,size: this.data.list.length}
    this.getList().finally(_ => {
      this.data.parmas = parmas
    })
  },1500,false),
  
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    app.ws.onList(false,this.refreshList.bind(this))
  },

  init() {
    this.setData({
      loading: true
    })
    this.getList().then(_=>{
      this.setData({
        loading: false
      })
    })
  },

  getList() {
    return new Promise(resolve => {
      const parmas = this.data.parmas
      Apimessagelist(parmas).then(res => {
        const { data, page  } = res
        const _data = data.map(item => {
          return {
            patient_id: item.patient_id,
            patient_name: item?.patient?.name ?? "",
            count: item.doctor_notice,
            message: item.type === 'txt' ? item.last_message.slice(0,50) : "[图片]",
            time: formatDate(item.last_time)
          }
        })
        const list = parmas.page === 1 ? _data : this.data.list.concat(_data)
        const finish = list.length >= page.total
        this.setData({
          list,
          finish,
        })
      }).finally(_=>{
        resolve()
      })
    })
  },

  onClickPatient(e){
    const index = e.currentTarget.dataset.index
    const item = {...this.data.list[index],message: undefined}

    wx.navigateTo({
      url: '/packageA/doctorIm/room/index?contact='+JSON.stringify(item),
      success: () => {
        this.setData({
          [`list[${index}].count`]: 0
        })
      }
    })
  },


  onClickUser(){
    wx.navigateTo({
      url: '/packageA/user/index',
    })
  },


  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.data.parmas.page = 1
    this.getList().then(_=> {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if(this.data.finish || this.data.loading) return
    this.data.parmas.page += 1 
    this.init()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})